package com.controller;

import com.alibaba.druid.util.StringUtils;
import com.common.NeedTokenByJWT;
import com.common.SkipTokenByJWT;
import com.common.pojo.LoginUser;
import com.entity.RespObject;
import com.entity.UserTable;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description: 测试controller
 * @author: GuoTong
 * @createTime: 2021-06-28 09:28
 * @since JDK 1.8 OR 11
 **/
@RestController
public class HelloController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    private final static Map<String, Object> RESP;

    static {
        RESP = new HashMap<>();
        RESP.put("author", "郭童");
        RESP.put("since", "JDK1.8");
        RESP.put("createTime", "2021-06-28 09:28");
        RESP.put("backFrame", "SpringBoot2.5.1");
        RESP.put("htmlTemp", "Thymeleaf");
    }

    @RequestMapping(value = "/hello", name = "web项目测试")
    public String gotoHelloWorld() {
        return "hello world！";
    }

    @RequestMapping(value = "/", name = "设置默认访问页面")
    public ModelAndView gotoIndexPage() {
        ModelAndView view = new ModelAndView("index");
        view.addObject("initData", RESP);
        return view;
    }

    @SkipTokenByJWT
    @PostMapping(value = "/login", name = "登录")
    public Object loginUser(@RequestBody LoginUser user) {
        UserTable userTable = userService.queryForEntity(user);
        if (userTable == null) {
            return RespObject.respNo("用户名或者密码错误");
        }
        String token = user.getToken(userTable);
        //缓存登录状态
        String emailIsRedisKeyByLife = userTable.getEmail();

        String dataRedis = (String) redisTemplate.opsForValue().get(emailIsRedisKeyByLife);
        if (StringUtils.isEmpty(dataRedis)) {
            redisTemplate.opsForValue().set(emailIsRedisKeyByLife, token);
            //设置过期时间； TimeUnit.MILLISECONDS  毫秒:设置默认时间是SECONDS秒：60秒
            redisTemplate.expire(emailIsRedisKeyByLife, 60, TimeUnit.MINUTES);

        }
        return RespObject.respLogin(token, userTable);
    }


    @GetMapping(value = "/getUserById", name = "根据ID获取数据")
    @NeedTokenByJWT
    public RespObject getUserTable(@RequestParam("id") int id) {
        UserTable user = userService.getUserById(id);
        if (user == null) {
            return RespObject.respNo("输入的ID无效");
        }
        return RespObject.respOk(user);
    }

}
